package middleware

import (
	"context"
	"gitee.com/qian/guser/model"
	"gitee.com/qian/guser/shared"
)

var Session = sessionService{}

type sessionService struct {
}

const (
	// 用户信息存放在Session中的Key
	sessionKeyUser = "SessionKeyUser"
)

func (s *sessionService) SetUser(ctx context.Context, user *model.Guser) error {
	return shared.Context.Get(ctx).Session.Set(sessionKeyUser, user)
}

func (s *sessionService) GetUser(ctx context.Context) *model.Guser {
	shareCtx := shared.Context.Get(ctx)
	if shareCtx != nil {
		v := shareCtx.Session.GetVar(sessionKeyUser)
		if !v.IsNil() {
			var user *model.Guser
			_ = v.Struct(&user)
			return user
		}
	}
	return nil
}

func (s *sessionService) RemoveUser(ctx context.Context) error {
	shareCtx := shared.Context.Get(ctx)
	if shareCtx != nil {
		return shareCtx.Session.Remove(sessionKeyUser)
	}
	return nil
}
